package GUI;

import java.awt.Color;
import java.awt.Component;
import java.awt.ComponentOrientation;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Insets;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Vector;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperPrintManager;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.JasperReportsContext;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.view.JasperViewer;

import CommonGui.ColorColumnRenderer;
import CommonGui.MyTableModel;
import Messages.MessageAddNewOrder;
import Messages.MessageAddNewOrderReply;
import Messages.MessageGetItemByID;
import Messages.MessageGetItemByIDReply;
import Messages.MessageGetSuppliersForItem;
import Messages.MessageGetSuppliersForItemReply;
import Messages.MessageShowAllInventory;
import Messages.MessageShowAllInventoryReply;
import Reports.Order;

public class PfOrderItemManual extends JPanel {
	/**
	 * Manual order of items. Each item can be ordered from 1 supplier.
	 * Resulting orders can be saved to Orders table and printed/saved in .pdf
	 * format.
	 * 
	 * @author Alex
	 * @since 10.12.12
	 * 
	 */
	private MainMenu mainMenu;

	private JPanel MainUpPanel;
	private JPanel MainLowPanel;
	private JPanel ItemsPanel;
	private JPanel MiddlePanel;
	private JPanel SuppliersPanel;
	private JPanel UpperControlsPanel;
	private JPanel OrderPanel;
	private JPanel LowerControlsPanel;
	private JPanel ItemsListPanel;
	private JPanel SuppliersListPanel;
	private JPanel OrdersListPanel;

	private Vector<Vector> itemsTable;
	private Vector<String> itemRow;
	private Vector<Vector> suppliersTable;
	private Vector<String> supplierRow;
	private Vector<Vector> ordersTable;
	private Vector<String> orderRow;

	private MyTableModel dtm;

	private JTable tblItems;
	private JTable tblSuppliers;
	private JTable tblOrders;

	public PfOrderItemManual(MainMenu mm) {
		super();
		this.mainMenu = mm;
		this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
		initialize();
	}

	private void initialize() {
		add(getMainUpPanel());
		add(getMainLowPanel());
	}

	private JPanel getMainUpPanel() {
		MainUpPanel = new JPanel();
		MainUpPanel.setLayout(new BoxLayout(MainUpPanel, BoxLayout.X_AXIS));
		MainUpPanel.add(getItemsPanel());
		MainUpPanel.add(getSuppliersPanel());

		//JPanel controls = getUpperControlsPanel();
		//controls.setAlignmentY(Component.TOP_ALIGNMENT);
		//MainUpPanel.add(controls);

		return MainUpPanel;
	}

	private JPanel getItemsPanel() {
		ItemsPanel = new JPanel();
		ItemsPanel.setBorder(new TitledBorder(UIManager
				.getBorder("TitleBorder.border"), "מוצרים",
				TitledBorder.CENTER, TitledBorder.TOP, null, null));
		ItemsPanel.setLayout(new BoxLayout(ItemsPanel, BoxLayout.Y_AXIS));
		ItemsPanel.getInsets(new Insets(0, 0, 0, 0));
		ItemsPanel.add(getItemsListPanel(ItemsPanel));

		return ItemsPanel;
	}

	private JPanel getItemsListPanel(JPanel parent) {
		ItemsListPanel = new JPanel();
		ItemsListPanel.setBackground(new Color(255, 250, 250));
		ItemsListPanel
				.setLayout(new BoxLayout(ItemsListPanel, BoxLayout.Y_AXIS));

		MessageShowAllInventory items = new MessageShowAllInventory();
		try {
			mainMenu.ms.client.sendToServer(items);
			MessageShowAllInventoryReply result = (MessageShowAllInventoryReply) mainMenu.ms.client
					.GetMessage();
			this.itemsTable = result.getResult();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		Vector<String> tblheader = new Vector<String>();
		tblheader.add("ID");
		tblheader.add("פריט");
		tblheader.add("קטגורייה");
		tblheader.add("תפוגה");
		tblheader.add("מינימום");
		tblheader.add("מקסימום");
		tblheader.add("יחידות");
		tblheader.add("כמות");

		dtm = new MyTableModel(this.itemsTable, tblheader);
		// System.out.println("Total items: " + dtm.getRowCount());
		tblItems = new JTable(dtm);
		DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
		centerRenderer.setHorizontalAlignment( JLabel.CENTER );
		for(int x=0;x<8;x++){
			tblItems.getColumnModel().getColumn(x).setCellRenderer( centerRenderer );
	        }
		tblItems.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
		
		int[] cols = { 0, 2, 3, 6 };
		hideColumns(tblItems, cols);

		TableColumn tm = tblItems.getColumnModel().getColumn(7);
		//tm.setCellRenderer(new ColorColumnRenderer(Color.green, Color.MAGENTA));

		tblItems.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
		tblItems.setFont(new Font("David", Font.BOLD, 16));
		tblItems.getTableHeader().setFont(new Font("Arial", Font.BOLD, 17));
		tblItems.getTableHeader().setBackground(new Color(173, 216, 230));
		tblItems.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
		tblItems.setRowHeight(30);
		tblItems.setFillsViewportHeight(true);
		tblItems.setGridColor(new Color(25, 25, 112));
		tblItems.setBackground(new Color(224, 255, 255));
		tblItems.setForeground(new Color(0, 0, 0));
		tblItems.setAutoCreateRowSorter(true);

		tblItems.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				
				if (e.getClickCount() == 1) {
					int row = tblItems.rowAtPoint(e.getPoint());
					int total = tblItems.getModel().getRowCount();

					if (row != -1) {
						// Vector<String> vec = (Vector<String>) dtm
						// .getDataVector().get(row);
						MyTableModel tm = (MyTableModel) tblItems.getModel();
						MyTableModel suppModel = (MyTableModel) tblSuppliers
								.getModel();

						Vector<String> vec = (Vector<String>) tm
								.getDataVector().get(row);
						String itemID = vec.get(0).trim();
						Vector<Vector> suppList;
						try {
						MessageGetSuppliersForItem msg = new MessageGetSuppliersForItem(
								itemID);
						
							mainMenu.ms.client.sendToServer(msg);
							MessageGetSuppliersForItemReply result = (MessageGetSuppliersForItemReply) mainMenu.ms.client
									.GetMessage();
							
							suppList = result.getSuppliers();
							
							tblSuppliers.removeAll();
							Vector<String> hdrs = new Vector<String>();

							hdrs.add("מחיר");
							hdrs.add("שם");
							hdrs.add("suppID");
							hdrs.add("itemID");

							MyTableModel dtm = new MyTableModel(suppList, hdrs);

							tblSuppliers.setModel(dtm);
							tblSuppliers.validate();
							DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
							centerRenderer.setHorizontalAlignment( JLabel.CENTER );
							for(int x=0;x<4;x++){
								tblSuppliers.getColumnModel().getColumn(x).setCellRenderer( centerRenderer );
						        }
							// tblSuppliers.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
							int[] cols = { 2, 3 };
							hideColumns(tblSuppliers, cols);

						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}

					}// if (row!=-1)
				}// if (e.getClickCount() == 1)
			}// public void mouseClicked(MouseEvent e)
		});

		JScrollPane itemsScroller = new JScrollPane(tblItems);
		itemsScroller.setPreferredSize(new Dimension(200, 200));
		ItemsListPanel.add(itemsScroller);

		return ItemsListPanel;
	}

	private JPanel getOrderPanel() {
		OrderPanel = new JPanel();
		OrderPanel.setBorder(new TitledBorder(UIManager
				.getBorder("TitleBorder.border"), "הזמנות",
				TitledBorder.CENTER, TitledBorder.TOP, null, null));
		OrderPanel.setLayout(new BoxLayout(OrderPanel, BoxLayout.Y_AXIS));
		OrderPanel.getInsets(new Insets(10, 10, 10, 10));
		OrderPanel.add(getOrdersListPanel());

		return OrderPanel;
	}

	private JPanel getOrdersListPanel() {
		OrdersListPanel = new JPanel();
		OrdersListPanel.setBackground(new Color(255, 250, 250));
		OrdersListPanel.setLayout(new BoxLayout(OrdersListPanel,
				BoxLayout.X_AXIS));

		// OrdersListModel = new DefaultListModel();

		Vector<String> tblheader = new Vector<String>();

		tblheader.add("itemID");
		tblheader.add("suppID");
		tblheader.add("סה''כ");
		tblheader.add("מחיר");
		tblheader.add("כמות");
		tblheader.add("ספק");
		tblheader.add("פריט");

		dtm = new MyTableModel(this.ordersTable, tblheader);

		tblOrders = new JTable(dtm);
		DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
		centerRenderer.setHorizontalAlignment( JLabel.CENTER );
		for(int x=0;x<7;x++){
			tblOrders.getColumnModel().getColumn(x).setCellRenderer( centerRenderer );
	        }
	//	tblOrders.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
		
		int[] cols = { 0, 1 };
		hideColumns(tblOrders, cols);

		tblOrders.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
		tblOrders.setFont(new Font("David", Font.BOLD, 16));
		tblOrders.getTableHeader().setFont(new Font("Arial", Font.BOLD, 17));
		tblOrders.getTableHeader().setBackground(new Color(173, 216, 230));
		tblOrders.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
		tblOrders.setRowHeight(30);
		tblOrders.setFillsViewportHeight(true);
		tblOrders.setGridColor(new Color(25, 25, 112));
		tblOrders.setBackground(new Color(224, 255, 255));
		tblOrders.setForeground(new Color(0, 0, 0));
		tblOrders.setAutoCreateRowSorter(true);

		JScrollPane ordersScroller = new JScrollPane(tblOrders);
		ordersScroller.setPreferredSize(new Dimension(200, 200));
		OrdersListPanel.add(ordersScroller);

		return OrdersListPanel;
	}

	private JPanel getMiddlePanel() {
		MiddlePanel = new JPanel();
		MiddlePanel.setLayout(new BoxLayout(MiddlePanel, BoxLayout.Y_AXIS));

		return MiddlePanel;
	}

	private JPanel getSuppliersPanel() {
		SuppliersPanel = new JPanel();
		SuppliersPanel.setBorder(new TitledBorder(UIManager
				.getBorder("TitleBorder.border"), "ספקים", TitledBorder.CENTER,
				TitledBorder.TOP, null, null));
		SuppliersPanel
				.setLayout(new BoxLayout(SuppliersPanel, BoxLayout.X_AXIS));
		SuppliersPanel.getInsets(new Insets(10, 10, 10, 10));
		SuppliersPanel.add(getSuppliersListPanel());

		return SuppliersPanel;
	}

	private JPanel getSuppliersListPanel() {
		SuppliersListPanel = new JPanel();
		SuppliersListPanel.setBackground(new Color(255, 250, 250));
		SuppliersListPanel.setLayout(new BoxLayout(SuppliersListPanel,
				BoxLayout.Y_AXIS));

		Vector<String> tblheader = new Vector<String>();

		tblheader.add("שם");
		tblheader.add("מחיר");
		tblheader.add("suppID");
		tblheader.add("itemID");

		dtm = new MyTableModel(null, tblheader);
		tblSuppliers = new JTable(dtm);
		DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
		centerRenderer.setHorizontalAlignment( JLabel.CENTER );
		for(int x=0;x<4;x++){
			tblSuppliers.getColumnModel().getColumn(x).setCellRenderer( centerRenderer );
	        }
		tblSuppliers.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);

		int[] cols = { 2, 3 };
		hideColumns(tblSuppliers, cols);

		TableColumn tm = tblSuppliers.getColumnModel().getColumn(2);
		tm.setCellRenderer(new ColorColumnRenderer(Color.green, Color.MAGENTA));

		DefaultTableCellRenderer righter = new DefaultTableCellRenderer();
		righter.setHorizontalAlignment(JLabel.RIGHT);
		tblSuppliers.getColumnModel().getColumn(1).setCellRenderer(righter);
		tblSuppliers.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
		tblSuppliers.setFont(new Font("David", Font.BOLD, 16));
		tblSuppliers.getTableHeader().setFont(new Font("Arial", Font.BOLD, 17));
		tblSuppliers.getTableHeader().setBackground(new Color(173, 216, 230));
		tblSuppliers.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
		tblSuppliers.setRowHeight(30);
		tblSuppliers.setFillsViewportHeight(true);
		tblSuppliers.setGridColor(new Color(25, 25, 112));
		tblSuppliers.setBackground(new Color(224, 255, 255));
		tblSuppliers.setForeground(new Color(0, 0, 0));
		tblSuppliers.setAutoCreateRowSorter(true);
		
		tblSuppliers.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				if(e.getClickCount() == 2){
					int rowIndex = tblSuppliers.rowAtPoint(e.getPoint());
					if(rowIndex != -1){
						String amountStr = (String) JOptionPane.showInputDialog(
								mainMenu, "נא להזין כמות היחידות להזמנה: \n");
						float amount;
						try {
							if (amountStr == null)
								throw (new NumberFormatException());
							else {
								amount = Float.parseFloat(amountStr);

								Vector<String> itemRow = (Vector<String>) ((MyTableModel) tblItems
										.getModel()).getDataVector().get(
										tblItems.convertRowIndexToModel(tblItems
												.getSelectedRow()));
								Vector<String> supplierRow = (Vector<String>) ((MyTableModel) tblSuppliers
										.getModel())
										.getDataVector()
										.get(tblSuppliers
												.convertRowIndexToModel(tblSuppliers
														.getSelectedRow()));

								System.out.println("Price: " + supplierRow.get(0)
										+ "\n" + "Supplier: name = "
										+ supplierRow.get(1) + ", ID = "
										+ supplierRow.get(3) + "\n"
										+ "Item: name = " + itemRow.get(1)
										+ ", ID = " + itemRow.get(0));

								// tblheader.add("itemID");
								// tblheader.add("suppID");
								// tblheader.add("סה''כ");
								// tblheader.add("מחיר");
								// tblheader.add("כמות"); ////// Orders table
								// columns
								// tblheader.add("ספק");
								// tblheader.add("פריט");

								/**
								 * Build data row for new order record
								 */
								Vector<String> orderRow = new Vector<String>();
								orderRow.add(itemRow.get(0));
								orderRow.add(supplierRow.get(3));
								orderRow.add(String.valueOf(amount
										* Float.parseFloat(supplierRow.get(0))));
								orderRow.add(supplierRow.get(0));
								orderRow.add(String.valueOf(amount));
								orderRow.add(supplierRow.get(1));
								orderRow.add(itemRow.get(1));
								// /////////////////////////////////////////////////

								/**
								 * Add order record to Orders table in Form
								 */
								MyTableModel orderModel = (MyTableModel) (tblOrders
										.getModel());
								orderModel.addRow(orderRow);
								tblOrders.setModel(orderModel);

								/**
								 * 
								 * Clear Suppliers table
								 */
								clearTable(tblSuppliers);

								/**
								 * Remove ordered item from Items table
								 */
								removeSelectedRow(tblItems);

							}

						} catch (NumberFormatException nfe) {
							JOptionPane.showMessageDialog(mainMenu,
									"רק ערך מספרי, בבקשה");
						}
					}
				}
			}
			
			
		});

		JScrollPane suppliersScroller = new JScrollPane(tblSuppliers);
		suppliersScroller.setPreferredSize(new Dimension(200, 200));
		SuppliersListPanel.add(suppliersScroller);

		return SuppliersListPanel;
	}

//	private JPanel getUpperControlsPanel() {
//		UpperControlsPanel = new JPanel();
//		UpperControlsPanel.setMinimumSize(new Dimension(100, 300));
//		UpperControlsPanel.setLayout(new BoxLayout(UpperControlsPanel,
//				BoxLayout.Y_AXIS));
//		UpperControlsPanel.setAlignmentY(Component.TOP_ALIGNMENT);
//		// UpperControlsPanel.setBackground(new Color(234,234,234));
//		UpperControlsPanel.add(getAddOrderButton());
//		UpperControlsPanel.add(Box.createVerticalGlue());
//
//		return UpperControlsPanel;
//	}

//	private JButton getAddOrderButton() {
//		JButton addBtn = new JButton("הוסף להזמנה");
//		addBtn.setAlignmentY(Component.TOP_ALIGNMENT);
//		addBtn.addMouseListener(new MouseAdapter() {
//			public void mouseClicked(MouseEvent e) {
//				if (tblSuppliers.getSelectedRow() == -1) {
//					JOptionPane.showMessageDialog(mainMenu, "נא לבחור ספק");
//				} else {
//					// System.out.println("clicked");
//					String amountStr = (String) JOptionPane.showInputDialog(
//							mainMenu, "נא להזין כמות היחידות להזמנה: \n");
//					float amount;
//					try {
//						if (amountStr == null)
//							throw (new NumberFormatException());
//						else {
//							amount = Float.parseFloat(amountStr);
//
//							Vector<String> itemRow = (Vector<String>) ((MyTableModel) tblItems
//									.getModel()).getDataVector().get(
//									tblItems.convertRowIndexToModel(tblItems
//											.getSelectedRow()));
//							Vector<String> supplierRow = (Vector<String>) ((MyTableModel) tblSuppliers
//									.getModel())
//									.getDataVector()
//									.get(tblSuppliers
//											.convertRowIndexToModel(tblSuppliers
//													.getSelectedRow()));
//
//							System.out.println("Price: " + supplierRow.get(0)
//									+ "\n" + "Supplier: name = "
//									+ supplierRow.get(1) + ", ID = "
//									+ supplierRow.get(3) + "\n"
//									+ "Item: name = " + itemRow.get(1)
//									+ ", ID = " + itemRow.get(0));
//
//							// tblheader.add("itemID");
//							// tblheader.add("suppID");
//							// tblheader.add("סה''כ");
//							// tblheader.add("מחיר");
//							// tblheader.add("כמות"); ////// Orders table
//							// columns
//							// tblheader.add("ספק");
//							// tblheader.add("פריט");
//
//							/**
//							 * Build data row for new order record
//							 */
//							Vector<String> orderRow = new Vector<String>();
//							orderRow.add(itemRow.get(0));
//							orderRow.add(supplierRow.get(3));
//							orderRow.add(String.valueOf(amount
//									* Float.parseFloat(supplierRow.get(0))));
//							orderRow.add(supplierRow.get(0));
//							orderRow.add(String.valueOf(amount));
//							orderRow.add(supplierRow.get(1));
//							orderRow.add(itemRow.get(1));
//							// /////////////////////////////////////////////////
//
//							/**
//							 * Add order record to Orders table in Form
//							 */
//							MyTableModel orderModel = (MyTableModel) (tblOrders
//									.getModel());
//							orderModel.addRow(orderRow);
//							tblOrders.setModel(orderModel);
//
//							/**
//							 * 
//							 * Clear Suppliers table
//							 */
//							clearTable(tblSuppliers);
//
//							/**
//							 * Remove ordered item from Items table
//							 */
//							removeSelectedRow(tblItems);
//
//						}
//
//					} catch (NumberFormatException nfe) {
//						JOptionPane.showMessageDialog(mainMenu,
//								"רק ערך מספרי, בבקשה");
//					}
//				}
//
//			}
//
//		});
//
//		return addBtn;
//	}

	private JPanel getMainLowPanel() {
		MainLowPanel = new JPanel();
		MainLowPanel.setLayout(new BoxLayout(MainLowPanel, BoxLayout.X_AXIS));
		MainLowPanel.add(getOrderPanel());

		JPanel controls = getLowerControlsPanel();
		controls.setMinimumSize(new Dimension(200, 300));
		MainLowPanel.add(controls);

		return MainLowPanel;
	}

	private JPanel getLowerControlsPanel() {
		LowerControlsPanel = new JPanel();
		LowerControlsPanel.setLayout(new BoxLayout(LowerControlsPanel,
				BoxLayout.Y_AXIS));
		LowerControlsPanel.setAlignmentY(Component.TOP_ALIGNMENT);
		JButton rmBtn = getRemoveOrderButton();
		JButton svBtn = getSaveOrderButton();
		//JButton pdfBtn = getPDFOrderButton();

		LowerControlsPanel.add(rmBtn);
		LowerControlsPanel.add(svBtn);
		//LowerControlsPanel.add(pdfBtn);
		LowerControlsPanel.setMinimumSize(new Dimension(100, 300));

		return LowerControlsPanel;
	}

	private JButton getRemoveOrderButton() {
		JButton removeOrderBtn = new JButton("מחק הזמנה");
		removeOrderBtn.setAlignmentY(Component.TOP_ALIGNMENT);
		removeOrderBtn.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				if (tblOrders.getSelectedRow() == -1) {
					JOptionPane.showMessageDialog(mainMenu, "נא לבחור הזמנה");
				} else {
					try {
						Vector<String> orderRow = (Vector<String>) ((MyTableModel) tblOrders
								.getModel()).getDataVector().get(
								tblOrders.convertRowIndexToModel(tblOrders
										.getSelectedRow()));

						String itemID = orderRow.get(0);
						Vector<String> item = new Vector<String>();

						MessageGetItemByID msg = new MessageGetItemByID(itemID);
						mainMenu.ms.client.sendToServer(msg);
						MessageGetItemByIDReply msgRes = (MessageGetItemByIDReply) mainMenu.ms.client
								.GetMessage();

						item = msgRes.getResult();

						if (item != null) {
							Vector<Vector> tbl = new Vector<Vector>();
							tbl.add(item);
							for (int i = 0; i < ((MyTableModel) tblItems
									.getModel()).getRowCount(); i++) {
								tbl.add((Vector<String>) ((MyTableModel) tblItems
										.getModel()).getDataVector().elementAt(
										i));
							}

							clearTable(tblItems);

							for (int i = 0; i < tbl.size(); i++) {
								((MyTableModel) tblItems.getModel()).addRow(tbl
										.get(i));
							}

							removeSelectedRow(tblOrders);
						} else {
							JOptionPane.showMessageDialog(mainMenu,
									"תקלה בתקשורת");
						}
					} catch (Exception rmoE) {
						JOptionPane.showMessageDialog(mainMenu, "תקלה בתקשורת");
						rmoE.printStackTrace();
					}
				}
			}
		});

		return removeOrderBtn;
	}

	private JButton getSaveOrderButton() {
		JButton saveOrderBtn = new JButton("שמור הזמנות");
		saveOrderBtn.setAlignmentY(Component.TOP_ALIGNMENT);
		saveOrderBtn.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {

				Vector<Vector> orders = new Vector<Vector>();
				
				
				orders = ((MyTableModel) tblOrders.getModel()).getDataVector();
				if (orders.size() == 0)
					JOptionPane.showMessageDialog(mainMenu,
							"נא להכין לפחות הזמנה אחת");
				else {
					Vector<DataObjects.Order> data = new Vector<DataObjects.Order>();
					
					for (int i = 0; i < orders.size(); i++) {
						DataObjects.Order order = new DataObjects.Order();
						order.setItem_id(orders.get(i).get(0).toString());// itemID
						order.setSupplier_id(orders.get(i).get(1).toString());// suppID
						order.setAmount(Float.parseFloat(orders.get(i).get(4).toString()));// amount
						order.setPrice(Float.parseFloat(orders.get(i).get(3).toString()));// price

						data.add(order);
						order = null;
					}

					try {
						MessageAddNewOrder msg = new MessageAddNewOrder(data);
						mainMenu.ms.client.sendToServer(msg);
						MessageAddNewOrderReply msgRes = (MessageAddNewOrderReply) mainMenu.ms.client
								.GetMessage();

						if (msgRes.getResult() == false)
							JOptionPane.showMessageDialog(mainMenu,
									"תקלה בתקשורת");
						else {
							clearTable(tblOrders);
							clearTable(tblSuppliers);
							JOptionPane.showMessageDialog(mainMenu,
									"ההזמנות נשמרו בהצלחה");
						}
					} catch (Exception soE) {
						soE.printStackTrace();
						JOptionPane.showMessageDialog(mainMenu, "תקלה בתקשורת");
					}
				}
			}
		});

		return saveOrderBtn;
	}

//	private JButton getPDFOrderButton() {
//		JButton pdfBtn = new JButton("הדפס PDF");
//		pdfBtn.setAlignmentY(Component.TOP_ALIGNMENT);
//		pdfBtn.addMouseListener(new MouseAdapter() {
//			public void mouseClicked(MouseEvent e) {
//
//				Vector<Vector> orders = new Vector<Vector>();
//				orders = ((MyTableModel) tblOrders.getModel()).getDataVector();
//				if (orders.size() == 0)
//					JOptionPane.showMessageDialog(mainMenu,
//							"נא להכין לפחות הזמנה אחת");
//				else {
//					Vector<DataObjects.Order> data = new Vector<DataObjects.Order>();
//					for (int i = 0; i < orders.size(); i++) {
//						DataObjects.Order order = new DataObjects.Order();
//						order.setItem_id(orders.get(i).get(0).toString());// itemID
//						order.setSupplier_id(orders.get(i).get(1).toString());// suppID
//						order.setAmount(Float.parseFloat(orders.get(i).get(4).toString()));// amount
//						order.setPrice(Float.parseFloat(orders.get(i).get(3).toString()));// price
//
//						data.add(order);
//						order = null;
//					}
//
//					try {
//						MessageAddNewOrder msg = new MessageAddNewOrder(data);
//						mainMenu.ms.client.sendToServer(msg);
//						MessageAddNewOrderReply msgRes = (MessageAddNewOrderReply) mainMenu.ms.client
//								.GetMessage();
//
//						if (msgRes.getResult() == false)
//							JOptionPane.showMessageDialog(mainMenu,
//									"תקלה בתקשורת");
//						else {
//							
//
//							try {
//								clearTable(tblOrders);
//								clearTable(tblSuppliers);
//
//								orders = msgRes.getSavedOrders();
//								ArrayList<Order> dataList = new ArrayList<Order>();
//
//								for (int i = 0; i < orders.size(); i++) {
//									Order o = new Order();
//									o.setOrder_id(Integer.parseInt(orders
//											.get(i).get(0).toString()));
//									o.setAmount(Float.parseFloat(orders.get(i)
//											.get(3).toString()));
//									o.setPrice(Float.parseFloat(orders.get(i)
//											.get(2).toString()));
//									o.setDate(orders.get(i).get(1).toString());
//									o.setItem_name(orders.get(i).get(4)
//											.toString());
//									o.setPhone(orders.get(i).get(9).toString()
//											+ "\n"
//											+ orders.get(i).get(10).toString()
//											+ "\n"
//											+ orders.get(i).get(11).toString());
//									o.setSupplier_name(orders.get(i).get(6)
//											.toString());
//									o.setAdress(orders.get(i).get(7).toString()
//											+ "\n"
//											+ orders.get(i).get(8).toString());
//
//									dataList.add(o);
//									System.out.println(o);
////									int j = -1;
////									System.out.println("order[" + ++j +"]" + orders.get(i).get(j).toString());
////									System.out.println("order[" + ++j +"]" + orders.get(i).get(j).toString());
////									System.out.println("order[" + ++j +"]" + orders.get(i).get(j).toString());
////									System.out.println("order[" + ++j +"]" + orders.get(i).get(j).toString());
////									System.out.println("order[" + ++j +"]" + orders.get(i).get(j).toString());
////									System.out.println("order[" + ++j +"]" + orders.get(i).get(j).toString());
////									System.out.println("order[" + ++j +"]" + orders.get(i).get(j).toString());
////									System.out.println("order[" + ++j +"]" + orders.get(i).get(j).toString());
////									System.out.println("order[" + ++j +"]" + orders.get(i).get(j).toString());
////									System.out.println("order[" + ++j +"]" + orders.get(i).get(j).toString());
////									System.out.println("order[" + ++j +"]" + orders.get(i).get(j).toString());
////									System.out.println("order[" + ++j +"]" + orders.get(i).get(j).toString());
////									System.out.println("order[" + ++j +"]" + orders.get(i).get(j).toString());
//								}
//								JRBeanCollectionDataSource reportData = new JRBeanCollectionDataSource(
//										dataList);
//								JasperPrint print = JasperFillManager
//										.fillReport(
//												"Reports/Orders/test.jasper",
//												null, reportData);
//								JasperViewer.viewReport(print);
//							} catch (JRException e1) {
//								e1.printStackTrace();
//							}
//
//						}
//					} catch (Exception soE) {
//						soE.printStackTrace();
//						JOptionPane.showMessageDialog(mainMenu, "תקלה בתקשורת");
//					}
//				}
//
//			}
//		});
//
//		return pdfBtn;
//	}

	private void hideColumns(JTable tbl, int[] cols) {
		/**
		 * Hiding columns of table.
		 * 
		 * @author Alex
		 * @since 10.12.12
		 * @param tbl
		 *            Reference to table
		 * @param cols
		 *            array of columns indecies to hide
		 */
		for (int i : cols) {
			tbl.getColumnModel().getColumn(i).setMinWidth(0);
			tbl.getColumnModel().getColumn(i).setMaxWidth(0);
			tbl.getColumnModel().getColumn(i).setPreferredWidth(0);
		}
	}

	private void removeSelectedRow(JTable tbl) {
		/**
		 * Removing selected row data from MODEL
		 * 
		 * @author Alex
		 * @since 10.12.12
		 * @param tbl
		 *            Reference to table to remove row from
		 */
		DefaultTableModel tblModel = (DefaultTableModel) tbl.getModel();
		int rowID = tbl.getSelectedRow();
		tblModel.removeRow(tbl.convertRowIndexToModel(rowID));
	}

	private void clearTable(JTable tbl) {
		/**
		 * Clearing table data from MODEL
		 * 
		 * @author Alex
		 * @since 10.12.12
		 * @param tbl
		 *            Reference to table to remove row from
		 */
		while (tbl.getModel().getRowCount() > 0)
			((DefaultTableModel) (tbl.getModel())).removeRow(0);
	}
}
